//
//  UIView+Extension.swift
//  afanti
//
//  Created by albert on 16/4/15.
//  Copyright © 2016年 albert. All rights reserved.
//

import UIKit

extension UIView {
    
    /** 尺寸 */
    var size: CGSize{
        get{
            return frame.size;
        }
        set{
            var frm = frame;
            frm.size = newValue;
            frame = frm;
        }
    }

    /** 宽度 */
    var width: CGFloat{
        get{
            return frame.size.width;
        }
        set{
            var frm = frame;
            frm.size.width = newValue;
            frame = frm;
        }
    }
    
    /** 高度 */
    var height: CGFloat{
        get{
            return frame.size.height;
        }
        set{
            var frm = frame;
            frm.size.height = newValue;
            frame = frm;
        }
    }
    
    /** X */
    var x: CGFloat{
        get{
            return frame.origin.x;
        }
        set{
            var frm = frame;
            frm.origin.x = newValue;
            frame = frm;
        }
    }
    
    /** Y */
    var y: CGFloat{
        get{
            return frame.origin.y;
        }
        set{
            var frm = frame;
            frm.origin.y = newValue;
            frame = frm;
        }
    }

    /** centerX */
    var centerX: CGFloat{
        get{
            return center.x;
        }
        set{
            var cter = center;
            cter.x = newValue;
            center = cter;
        }
    }
    
    /** centerY */
    var centerY: CGFloat{
        get{
            return center.y;
        }
        set{
            var cter = center;
            cter.y = newValue;
            center = cter;
        }
    }
    
    /** 判断控件是否真正显示在窗口范围内 */
    func isShowingOnKeyWindow(selfFrame: CGRect, superView: UIView) -> Bool{
        //主窗口
        let keyWindow = UIApplication.sharedApplication().keyWindow;
        
        //得到self在主窗口中的frame
        // 转换self的frame，写成nil就是转为以屏幕左上角为原点
        //CGRect newFrame = [self.superview convertRect:subview.frame toView:nil];
        //let newFrame = [keyWindow convertRect:self.frame fromView:self.superview]
        let newFrame = keyWindow?.convertRect(selfFrame, fromView: superView)
        
        //窗口的bounds
        let windowBounds = keyWindow!.bounds;
        
        //主窗口的bounds 和 subview主窗口左上角为原点的frame 是否有重叠
        // CGRectIntersectsRect(newFrame, windowBounds)比较两个rect是否有交叉
        let intersects = CGRectIntersectsRect(newFrame!, windowBounds);
        
        //返回。控件没有被添加到窗口上时，控件的window == nil
        return !self.hidden && self.alpha > 0.01 && intersects && self.window == keyWindow;
    }
    
    /** 从xib中加载view */
    class func viewFromXib(className: String) -> AnyObject{
        
        return NSBundle.mainBundle().loadNibNamed(className, owner: nil, options: nil).last!
        //[[[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self) owner:nil options:nil] lastObject];
    }
}
